<template>
  <view class="add-form-container">
    <!-- 使用封装的页面头部组件 -->
    <page-header
      :title="isEdit ? '编辑采收记录' : '新增采收记录'"
    ></page-header>
    
    <!-- 使用地块选择器组件 -->
    <land-selector 
      ref="landSelector"
      @selection-change="handleLandSelectionChange"
    ></land-selector>

    <!-- 使用条田选择器组件 -->
    <section-selector 
        ref="sectionSelector" 
        @areaChange="handleAreaChange"
        @usersChange="handleUsersChange"></section-selector>

    <!-- 地块信息 -->
    <view class="basic-info">
      <view class="section-title">地块信息</view>

      <uni-forms
        ref="form"
        :modelValue="formData"
        :rules="rules"
        validateTrigger="bind"
        label-position="top"
        class="farm-form"
      >
        <uni-forms-item label="面积" name="area" required>
          <uni-easyinput
            type="digit"
            v-model="formData.area"
            placeholder="请输入面积"
            disabled
          >
            <template #right>
              <text class="input-unit">亩</text>
            </template>
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="采收时间" name="harvestDate" required>
          <uni-datetime-picker
            type="date"
            v-model="formData.harvestDate"
            :border="false"
          >
            <view class="uni-date-picker-container">
              <text
                :class="{
                  placeholder: !formData.harvestDate,
                }"
                >{{
                  formData.harvestDate || "请选择采收时间"
                }}</text
              >
              <view class="date-icon">
                <roc-icon-plus
                  type="fas"
                  name="calendar-alt"
                  :size="18"
                  color="#999"
                ></roc-icon-plus>
              </view>
            </view>
          </uni-datetime-picker>
        </uni-forms-item>
      </uni-forms>
    </view>

    <!-- 作物信息 -->
    <view class="basic-info">
      <view class="section-title">作物信息</view>

      <uni-forms
        ref="cropForm"
        :modelValue="formData"
        validateTrigger="bind"
        label-position="top"
        class="farm-form"
      >
        <uni-forms-item
          label="作物类型"
          name="cropType"
          :label-width="200"
          required
        >
          <uni-data-select
            v-model="formData.cropType"
            :localdata="cropTypesData"
            placeholder="请选择作物类型"
            @change="handleCropTypeChange"
          ></uni-data-select>
        </uni-forms-item>

        <uni-forms-item label="作物品种" name="cropVarietyId" required>
          <uni-data-select
            v-model="formData.cropVarietyId"
            :localdata="currentCropVarieties"
            placeholder="请选择作物品种"
          ></uni-data-select>
        </uni-forms-item>
      </uni-forms>
    </view>

    <!-- 收成数据 -->
    <view class="basic-info">
      <view class="section-title">收成数据</view>

      <uni-forms
        ref="harvestForm"
        :modelValue="formData"
        validateTrigger="bind"
        label-position="top"
        class="farm-form"
      >
        <uni-forms-item label="净重" name="netWeight" required>
          <uni-easyinput
            type="digit"
            v-model="formData.netWeight"
            placeholder="请输入净重"
          >
            <template #right>
              <text class="input-unit">kg</text>
            </template>
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="成熟度" name="maturityLevel">
          <view class="slider-container">
            <slider 
              :value="formData.maturityLevel" 
              @change="onMaturityChange" 
              min="0" 
              max="100" 
              show-value 
              activeColor="#2EB57D"
            />
            <!-- <text class="slider-value">{{ formData.maturityLevel }}%</text> -->
          </view>
        </uni-forms-item>

        <uni-forms-item label="损耗" name="lossRate">
          <uni-easyinput
            type="digit"
            v-model="formData.lossRate"
            placeholder="请输入损耗比例"
          >
            <template #right>
              <text class="input-unit">%</text>
            </template>
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="等级" name="qualityGrade">
          <view class="radio-group">
            <view
              v-for="option in qualityGradeOptions"
              :key="option.value"
              class="radio-item"
              @click="formData.qualityGrade = option.value"
            >
              <view class="radio-circle" :class="{ active: formData.qualityGrade === option.value }">
                <view class="radio-inner" v-if="formData.qualityGrade === option.value"></view>
              </view>
              <text class="radio-label">{{ option.text }}</text>
            </view>
          </view>
        </uni-forms-item>

        <uni-forms-item label="负责人" name="personInCharge" required>
          <uni-easyinput
            v-model="formData.personInCharge"
            placeholder="请输入负责人姓名"
            disabled></uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="备注" name="remark">
          <uni-easyinput
            type="textarea"
            v-model="formData.remark"
            placeholder="请输入备注说明"
            :maxlength="200"
          ></uni-easyinput>
        </uni-forms-item>
      </uni-forms>
    </view>

    <!-- 现场照片 -->
    <view class="photo-section">
      <view class="section-title">现场照片</view>

      <image-uploader
        ref="imageUploader"
        :images="formData.images"
        :maxCount="9"
        @update:images="updateImages"
      />
    </view>

    <view class="submit-btn-container">
      <view class="submit-btn" @click="submitForm">点击上传</view>
    </view>
  </view>
</template>

<script>
import PageHeader from "@/components/PageHeader/index.vue";
import LandSelector from "@/components/LandSelector/index.vue";
import SectionSelector from "@/components/SectionSelector/index.vue";
import ImageUploader from "@/components/ImageUploader/index.vue";
import { harvest } from '@/utils/api/index.js';
import { formatDate, getDefaultDateRange } from '@/utils/util.js';
import { mapGetters, mapActions } from "vuex";

export default {
  components: {
    PageHeader,
    LandSelector,
    SectionSelector,
    ImageUploader
  },
  computed: {
    ...mapGetters({
      getDictByType: "getDictByType",
      getDictLabel: "getDictLabel",
      userInfo: "getUserInfo"
    }),
  },
  data() {
    const defaultDateRange = getDefaultDateRange()
    return {
      isEdit: false,
      editId: null,
      selectedLands: [],
      selectedSections: [],
      formData: {
        startDate: defaultDateRange.dateRange[0],
        harvestDate: defaultDateRange.dateRange[0],
        plotId: "",
        fieldId: "",
        area: "",
        cropType: "",
        cropName: "",
        cropVariety: "",
        cropVarietyId: "",
        netWeight: "",
        maturityLevel: 80,
        lossRate: "5",
        qualityGrade: "良",
        personInCharge: "",
        personInId: "",
        remark: "",
        remarks: "",
        images: []
      },
      rules: {
        area: {
          rules: [
            {
              required: true,
              errorMessage: "请输入面积",
            },
            {
              format: "number",
              errorMessage: "请输入有效的数字",
            },
          ],
        },
        harvestDate: {
          rules: [
            {
              required: true,
              errorMessage: "请选择采收时间",
            },
          ],
        },
        cropType: {
          rules: [
            {
              required: true,
              errorMessage: "请选择作物类型",
            },
          ],
        },
        cropVarietyId: {
          rules: [
            {
              required: true,
              errorMessage: "请选择作物品种",
            },
          ],
        },
        netWeight: {
          rules: [
            {
              required: true,
              errorMessage: "请输入净重",
            },
            {
              format: "number",
              errorMessage: "请输入有效的数字",
            },
          ],
        },
        personInCharge: {
          rules: [
            {
              required: true,
              errorMessage: "请输入负责人",
            },
          ],
        }
      },
      cropTypesData: [],
      currentCropVarieties: [],
      qualityGradeOptions: []
    };
  },
  onLoad(options) {
    // 加载字典数据
    this.loadDictData();
    
    if (options.id) {
      this.isEdit = true;
      this.editId = options.id;
      this.loadHarvestRecord(options.id);
    } else {
      // 设置默认的负责人和负责人ID
      console.log('用户信息', this.userInfo)
      this.formData.personInId = this.userInfo.id
      this.formData.personInCharge = this.userInfo.nickname
    }
  },
  methods: {
    ...mapActions(["getDictByType"]),

    // 加载字典数据
    async loadDictData() {
      try {
        uni.showLoading({ title: "加载字典数据..." });

        // 加载作物类型字典
        await this.getDictByType("crop_name_type");
        this.cropTypesData = this.formatDictToSelectData("crop_name_type");
        console.log("作物类型字典:", this.cropTypesData);

        // 加载等级字典
        await this.getDictByType("harvesting_management_level");
        this.qualityGradeOptions = this.formatDictToSelectData("harvesting_management_level");

        uni.hideLoading();
      } catch (error) {
        console.error("加载字典数据失败:", error);
        uni.hideLoading();
        uni.showToast({
          title: "加载字典数据失败",
          icon: "none",
        });
      }
    },

    // 将字典数据格式化为下拉选择框所需的格式
    formatDictToSelectData(dictType) {
      const dictList = this.getDictByType(dictType);
      return dictList.map((item) => ({
        value: item.value,
        text: item.label,
      }));
    },
    
    // 加载采收记录详情
    async loadHarvestRecord(id) {
      try {
        uni.showLoading({ title: '加载中...' });
        
        // 调用API获取采收记录详情
        const res = await harvest.getHarvestDetail(id);
        
        if (res.code === 0 && res.data) {
          const harvestData = res.data;
          
          // 处理图片数据
          const images = this.formatImages(harvestData.images);
          
          // 设置表单数据
          this.formData = {
            ...harvestData,
            harvestDate: harvestData.startDate || formatDate(new Date()), // 使用开始日期作为采收日期
            area: harvestData.area ? harvestData.area.toString() : "",
            netWeight: harvestData.netWeight ? harvestData.netWeight.toString() : "",
            lossRate: harvestData.lossRate ? harvestData.lossRate.toString() : "5",
            maturityLevel: harvestData.maturityLevel || 80,
            qualityGrade: harvestData.qualityGrade || "良",
            images: images
          };
          
          // 设置作物类型后，加载对应的品种选项
          this.handleCropTypeChange();
          
          // 等待组件加载完成后，设置地块选择状态
          this.$nextTick(() => {
            // 确保组件已完全加载
            setTimeout(() => {
              // 设置地块选择器中选中的地块
              if (this.$refs.landSelector && harvestData.plotId) {
                this.$refs.landSelector.setSelectedLands(harvestData.plotId);
                this.updateSelectedLands();

                // 更新条田选择器的地块ID
                if (this.$refs.sectionSelector) {
                  this.$refs.sectionSelector.setSelectedParcels(this.selectedLands);

                  // 设置条田选择状态
                  if (harvestData.fieldId) {
                    this.$refs.sectionSelector.setSelectedFields(harvestData.fieldId);
                    this.updateSelectedSections();
                  }
                }
              }
            }, 800);
          });
        } else {
          uni.showToast({
            title: res.msg || '获取数据失败',
            icon: 'none'
          });
        }
        uni.hideLoading();
      } catch (error) {
        console.error('加载采收记录失败:', error);
        uni.hideLoading();
        uni.showToast({
          title: '加载数据失败',
          icon: 'none'
        });
      }
    },
    
    // 格式化图片字段，将字符串或JSON字符串转为数组
    formatImages(images) {
      if (!images) return [];
      
      // 如果是JSON字符串，先解析
      if (typeof images === 'string') {
        try {
          if (images.startsWith('[')) {
            // 尝试解析JSON字符串
            return JSON.parse(images);
          } else if (images.includes(',')) {
            // 逗号分隔的字符串
            return images.split(',');
          }
          // 单个图片URL
          return [images];
        } catch (e) {
          console.error('解析图片数据失败:', e);
          return [];
        }
      }
      
      // 已经是数组则直接返回
      return Array.isArray(images) ? images : [];
    },
    
    // 地块选择变化
    handleLandSelectionChange() {
      this.updateSelectedLands();
    },
    handleAreaChange(area) {
      this.formData.area = area;
    },

    handleUsersChange(users) {
      this.formData.personInId = users.map((item) => item.userId).join(',');
      this.formData.personInCharge = users.map((item) => item.userName).join(',');
    },

    // 更新选中的地块数据
    updateSelectedLands() {
      if (this.$refs.landSelector) {
        this.selectedLands = this.$refs.landSelector.getSelectedLands();
        console.log("更新选中的地块:", this.selectedLands);

        // 当地块选择变化时，更新条田选择器
        if (this.$refs.sectionSelector) {
          this.$refs.sectionSelector.setSelectedParcels(this.selectedLands);
          // 更新选中的条田
          this.updateSelectedSections();
        }
      }
    },

    // 更新选中的条田数据
    updateSelectedSections() {
      if (this.$refs.sectionSelector) {
        this.selectedSections = this.$refs.sectionSelector.getSelectedSections();
        console.log("更新选中的条田:", this.selectedSections);
      }
    },
    
    // 作物类型变化
    async handleCropTypeChange() {
      const cropType = this.formData.cropType;
      this.formData.cropName = cropType;
      
      if (cropType) {
        try {
          // 加载对应的作物品种字典
          await this.getDictByType(cropType);
          this.currentCropVarieties = this.formatDictToSelectData(cropType);
        } catch (error) {
          console.error("获取作物品种字典失败:", error);
          this.currentCropVarieties = [];
        }
      } else {
        this.currentCropVarieties = [];
      }
      
      // 重置作物品种
      if (
        this.formData.cropVarietyId &&
        !this.currentCropVarieties.some(
          (item) => item.value === this.formData.cropVarietyId
        )
      ) {
        this.formData.cropVarietyId = "";
      }
    },
    
    // 成熟度变化
    onMaturityChange(e) {
      this.formData.maturityLevel = e.detail.value;
    },
    
    // 更新图片
    updateImages(images) {
      this.formData.images = images;
    },
    
    // 表单验证
    validateForm() {
      // 更新选中的地块和条田
      this.updateSelectedLands();
      this.updateSelectedSections();
      
      // 检查是否选择了地块
      if (!this.$refs.landSelector.validate()) {
        uni.showToast({
          title: "请选择至少一个地块",
          icon: "none",
        });
        return false;
      }

      if (!this.$refs.sectionSelector.validate()) {
        uni.showToast({
          title: "请选择至少一个条田",
          icon: "none",
        });
        return false;
      }
      
      try {
        // 验证地块表单
        this.$refs.form.validate();
        
        // 验证作物表单
        this.$refs.cropForm.validate();
        
        // 验证收成数据表单
        this.$refs.harvestForm.validate();
        
        return true;
      } catch (errors) {
        console.error('表单验证失败:', errors);
        return false;
      }
    },
    
    // 提交表单
    submitForm() {
      console.log(this.formData);
      // 使用uni-forms的验证方法
      if (this.validateForm()) {
        this.submitFormData();
      }
    },
    
    // 提交表单数据
    async submitFormData() {
      try {
        // 检查损耗率
        const lossRate = Number(this.formData.lossRate);
        if (lossRate > 100) {
          uni.showToast({
            title: '损耗率不能超过100%',
            icon: 'none',
            duration: 2000
          });
          return;
        }

        uni.showLoading({ title: '提交中...' });
        
        // 获取选中的地块和条田
        this.updateSelectedLands();
        this.updateSelectedSections();
        
        // 提取地块和条田ID
        let plotId = this.selectedLands.map(item => item.id);
        let fieldId = this.selectedSections.map(item => item.id);
        let plotName = this.selectedLands.map((item) => item.name);
        let fieldName = this.selectedSections.map((item) => item.name);
        
        // 使用 imageUploader 组件的 getImageList 方法获取图片列表
        const imageList = this.$refs.imageUploader.getImageList();
        
        // 准备提交的数据
        const submitData = {
          ...this.formData,
          startDate: this.formData.harvestDate,
          endDate: this.formData.harvestDate,
          plotId: plotId?.join(','), // 地块ID，逗号分隔
          fieldId: fieldId?.join(','), // 条田ID，逗号分隔
          plotName: plotName?.join(','),
          fieldName: fieldName?.join(','),
          // 获取作物名称的显示文本
          cropName: this.getDictLabel('crop_name_type', this.formData.cropType) || this.formData.cropType,
          // 获取作物品种的显示文本
          // cropVarietyName: this.getDictLabel(this.formData.cropType, this.formData.cropVariety) || this.formData.cropVariety,
          // 将图片数组转为字符串，使用逗号分隔
          images: imageList.join(',')
        };
        
        // 如果是编辑模式，需要添加ID
        if (this.isEdit) {
          submitData.id = this.editId;
          await harvest.updateHarvest(submitData);
        } else {
          await harvest.createHarvest(submitData);
        }
        
        uni.hideLoading();
        uni.showToast({
          title: this.isEdit ? '更新成功' : '添加成功',
          icon: 'success',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              // 返回上一页并刷新
              uni.navigateBack({
                delta: 1,
              });
            }, 1500);
          },
        });
      } catch (error) {
        uni.hideLoading();
        console.error('提交失败:', error);
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'none',
          duration: 2000,
        });
      }
    }
  }
};
</script>

<style lang="scss">
.radio-group {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.radio-item {
  display: flex;
  align-items: center;
  margin-right: 30rpx;
  margin-bottom: 20rpx;
}

.radio-circle {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10rpx;
}

.radio-circle.active {
  border-color: #2EB57D;
}

.radio-inner {
  width: 24rpx;
  height: 24rpx;
  border-radius: 50%;
  background-color: #2EB57D;
}

.radio-label {
  font-size: 28rpx;
}

.slider-container {
  padding: 10rpx 0;
}

.slider-value {
  font-size: 28rpx;
  color: #666;
  margin-left: 10rpx;
}
</style> 